﻿
$(function () {

    // scroll star
    $('.inlineBlocka').click(function () {
        $('html, body').animate({
            scrollTop: ($("#productCommentTab").offset().top - 36)
        }, 1000);
    });
    // SIZE PRODUCT ----------------------------------------------------------------------------
    LoadEventSize();
    // COLOR PRODUCT ---------------------------------------------------------------------------
    LoadEventColor();
    // SLIDE IMAGE -----------------------------------------------------------------------------
    //runSlide();

    //rating star ------------------------------------------------------------------------------
    $('#example-f').barrating({ showSelectedRating: false });
    //binh chon trong chi tiet san pham
    $('.br-widget a').click(function () {
        $('body').append('<div class="bgface" style="opacity: 0.5;"></div>');
        $('.bgface').fadeIn();
        var hBody = $('body').height();
        var wBody = $('body').width();
        var top = (hBody - $('.popup-addrate-login').height()) / 2;
        var left = (wBody - $('.popup-addrate-login').width()) / 2;
        $('.popup-addrate-login').css({ 'position': 'fixed', 'top': top + 'px', 'left': left + 'px' });
        $('.popup-addrate-login').fadeIn();
        var data = $(this).attr('data-rating-value');
        $('.popup-addrate-login input[name$=rate]').val(data);
        closeFace();
    });

    //dong lop mat na
    function closeFace() {
        //tat tat ca popup
        $('.bgface').click(function () {
            $(this).remove();
            $('.iconLoading').remove();
            //dong box fast login
            $('.popup-addrate-login').hide();
            $('.FromFastLogin').hide();
            $('.inputError').hide();
        });
    }
    //btn dong box login
    $('.CloseBoxLogin').click(function () {
        $('.bgface').click();
    });
    //product detail: click vao dang nhap hien thi popup
    $('.lnkFastLogin').click(function () {
        $(this).parent().children('.FromFastLogin').stop().slideToggle();
    });
    //End rating star ------------------------------------------------------------------------------


    //het hang hien thi nut va thong bao
    $('input.btnHetHang').click(function () {
        alert('Sản phẩm này đã hết hàng ! \n Quý khách vui lòng liên hệ cửa hàng để biết thông tin chi tiết.');
        return false;
    });

    function runSlide() {
        $('.icon-arrow-right').unbind('click');
        $('.icon-arrow-left').unbind('click');

        var itemWidth = 59;
        var itemCount = $('.slide-image a.item-slide-show').length;
        var itemSlideShow = $('.slide-image a.item-slide-show');
        $('.slide-image a.item-slide-hidden').css({ 'left': '-2000px' });
        var cursorLeft = 0;
        $('.slide-image-wrapper').css({
            'width': '295px',
            'overflow': 'hidden',
            'margin': '0 auto'
        });
        $('.slide-image').css({
            'width': itemWidth * itemCount,
            'position': 'relative',
            'height': '57px'
        });

        $('.slide-image a.item-slide:visible').css({
            'position': 'absolute'
        });

        itemSlideShow.each(function () {
            $(this).css({
                'left': cursorLeft
            });
            cursorLeft += itemWidth;
        });

        if (itemCount > 5) {
            slideRight($('.icon-arrow-right'), itemSlideShow, itemCount, itemWidth);
            slideLeft($('.icon-arrow-left'), itemSlideShow, itemCount, itemWidth);
        } else {
            $('.icon-arrow-right').unbind('click');
            $('.icon-arrow-left').unbind('click');
        }
    }

    function slideLeft(obj, itemSlideShow, itemCount, itemWidth) {
        obj.click(function () {
            obj.unbind('click');
            itemSlideShow.stop().animate({ 'left': '-=' + itemWidth }, 500, function () {
                itemSlideShow.each(function () {
                    if ($(this).css('left') == ('-' + itemWidth + 'px')) {
                        $(this).css('left', (itemWidth * itemCount - itemWidth) + 'px');
                    }
                });
                slideLeft(obj, itemSlideShow, itemCount, itemWidth);
            });
        });
    }

    function slideRight(obj, itemSlideShow, itemCount, itemWidth) {
        obj.click(function () {
            obj.unbind('click');
            $(itemSlideShow).each(function () {
                if ($(this).css('left') == (itemWidth * itemCount - itemWidth) + 'px') {
                    $(this).css('left', ('-' + itemWidth + 'px'));
                }
            });
            itemSlideShow.stop().animate({ 'left': '+=' + itemWidth }, 500, function () {
                slideRight(obj, itemSlideShow, itemCount, itemWidth);
            });
        });
    }


    $('.pDetail-headerTab ul li').click(function () {
        var idx = $(this).index();
        $('.pDetail-headerTab ul li').removeClass('headerTab-ac');
        $(this).addClass('headerTab-ac');
        $('.pDetail-Content-wrap .pDetail-Content-Item').removeClass('ContentItem-ac');
        $('.pDetail-Content-wrap .pDetail-Content-Item:eq(' + idx + ')').addClass('ContentItem-ac');
    });


    // Show and hide images by color ------------------------------------------------------------
    $('.p-color span.pc-color').click(function () {
        var id = $(this).attr('id');
        $('div.zoom-desc a.cloud-zoom-gallery').removeClass('item-slide-show').addClass('item-slide-hidden');
        $('div.zoom-desc a.' + id).removeClass('item-slide-hidden').addClass('item-slide-show');

        var itemFirstShow = $('div.zoom-desc a.' + id).eq(0);
        var img1200X1200 = itemFirstShow.attr('href');
        var img319X300 = itemFirstShow.children().attr('src').replace('width=50&height=50', 'width=319&height=300');
        $('.zoom-small-image').html('<a href="' + img1200X1200 + '" class="cloud-zoom" id="zoom1" rel="zoomWidth:480,zoomHeight: 320,adjustX: 10, adjustY:-4" onclick="return false;">' +
            '<img src="' + img319X300 + '" alt="" title=""/>' +
            '</a>');

        $('.cloud-zoom, .cloud-zoom-gallery').CloudZoom({
            zoomWidth: '392',
            zoomHeight: '477'
        });

        //runSlide();
    });

    // HISTORY PRODUCT VIEWED JQUERY COOKIES ------------------------------------------------------------------------------
    //Lay ve Id san pham moi nhat ma khach hang vua xem
    if (typeof $.cookie('productHistory') != 'undefined') {
        var dataHis = JSON.parse($.cookie('productHistory'));
        var idLast = dataHis.length - 1;
        $.ajax({
            type: 'POST',
            dataType: 'html',
            cache: false,
            url: '/ProductDetail/ProductDetailRight',
            data: { productIdHis: dataHis[idLast].ProductId },
            success: function (data) {
                $('#plcSpqt').append(data);
                dinhBoxSpqt(); //bam dinh box
            },
            error: function (e) {
                alert(e);
            }
        });
    }
    //$.cookie.json = true;
    //$.removeCookie('productHistory');
    if (typeof $.cookie('productHistory') != 'undefined') {
        var flag = false;
        var productId = $('#productId').val();
        var data = JSON.parse($.cookie('productHistory'));
        $.ajax({
            type: 'POST',
            dataType: 'html',
            cache: false,
            url: '/ProductDetail/ProductViewedHistory',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(data),
            success: function (data) {
                $('.bb_pdetail').children('.box-p-history').empty();
                $('.bb_pdetail').append(data);
            },
            error: function (e) {
                alert('Đã có lỗi xảy ra');
            }
        });

        for (var i = 0; i < data.length; i++) {
            if (data[i].ProductId == productId) {
                flag = true;
                break;
            }
        }

        //neu san pham nay chua co trong history
        if (!flag) {
            var idLast = data.length - 1;
            var productId = $('#productId').val();
            var imagePath = $('.slide-image a').eq(0).children('img').attr('src').replace('?width=50&height=50', '?width=188&height=188');
            var url = document.URL;
            var rootPrice = $('#rootPriceProduct').val();
            var promotionPrice = $('#promotionPrice').val() == '' ? '0' : $('#promotionPrice').val();
            var name = $('#productName').val();
            var stt = data[idLast].STT + 1;
            var obj = { ProductId: productId, ImagePath: imagePath, Url: url, RootPrice: rootPrice, PromotionPrice: promotionPrice, Name: name, STT: stt };
            data.push(obj);
            $.cookie('productHistory', JSON.stringify(data));
        }
    } else {
        var productId = $('#productId').val();
        var imagePath = $('.slide-image a').eq(0).children('img').attr('src').replace('?width=50&height=50', '?width=188&height=188');
        var url = document.URL;
        var rootPrice = $('#rootPriceProduct').val();
        var promotionPrice = $('#promotionPrice').val() == '' ? '0' : $('#promotionPrice').val();
        var name = $('#productName').val();
        var stt = 1;
        var obj = [
            { ProductId: productId, ImagePath: imagePath, Url: url, RootPrice: rootPrice, PromotionPrice: promotionPrice, Name: name, STT: stt }
        ];

        $.cookie('productHistory', JSON.stringify(obj));
    }




    // ADD RATE ------------------------------------------
    $('.boxRegComment .bnt-addRate').click(function () {
        //alert('ok');
        var rtn = true;
        var name = $('.boxRegComment .inputNameRate').val();
        var email = $('.boxRegComment .inputEmailRate').val();
        //alert(name + '/' + email);
        $('.boxRegComment .inputError').hide();

        if (email == '' || email == undefined) {
            $('.boxRegComment .inputEmailRate').next().text('Mời bạn nhập email').fadeIn();
            rtn = false;
        } else if (!isValidEmailAddress(email)) {
            $('.boxRegComment .inputEmailRate').next().text('Email không đúng đinh dạng').fadeIn();
            rtn = false;
        } else if (name == '' || name == undefined) {
            $('.boxRegComment .inputNameRate').next().text('Mời bạn nhập họ và tên').fadeIn();
            rtn = false;
        }
        return rtn;
    });

    $('.lnkRateLogin .lnkFastLogin').click(function () {
        $('.boxRegComment .boxRegComment').slideToggle();
    });
    //LOGIN POPUP PRODUCT DETAIL
    $('.lnkRateLogin .bntFastLogin').click(function () {
        //alert('ok');
        var rtn = true;
        var email = $('.lnkRateLogin .loginFastEmail').val();
        var pass = $('.lnkRateLogin .loginFastPass').val();
        //alert(name + '/' + email);
        $('.lnkRateLogin .inputError').hide();
        if (email == '' || email == undefined) {
            $('.lnkRateLogin .loginFastEmail').parent().children('.inputError').text('Mời bạn nhập email').show();
            rtn = false;
        } else if (!isValidEmailAddress(email)) {
            $('.lnkRateLogin .loginFastEmail').parent().children('.inputError').text('Email không đúng đinh dạng').show();
            rtn = false;
        } else if (pass == '' || pass == undefined) {
            $('.lnkRateLogin .loginFastPass').parent().children('.inputError').text('Mời bạn nhập password').show();
            rtn = false;
        }
        return rtn;

    });

    $('.rate-comment .bnt-addComment').click(function () {
        var rtn = true;
        //khong nhap rong
        var title = $('.rate-comment input[name$=txtCommentTitle]');
        var content = $('.rate-comment textarea[name$=txtComment]');
        var fullName = $('.rate-comment input[name$=txtAccountNameComment]');
        $('.rate-comment .inputError').hide();
        if (title.val() == '') {
            title.parent().children('.inputError').text('Mời bạn nhập tiêu đề cho bình luận').fadeIn();
            title.focus();
            rtn = false;
        } else if (content.val() == '') {
            content.parent().parent().children('.inputError').text('Mời bạn nhập nội dung cho bình luận').fadeIn();
            content.focus();
            rtn = false;
        } else if (fullName.val() == '') {
            fullName.parent().children('.inputError').text('Mời bạn nhập họ và tên').fadeIn();
            fullName.focus();
            rtn = false;
        }

        return rtn;
    });


    //Add product together first
    $('.chkTogether span').click(function () {
        //alert('ok');
        var cmd = $(this);
        var chk = cmd.parent().find('input[name$=together]');
        var imap = chk.attr('imap'); // Id cua chk hien tai
        chk.attr("checked", !chk.is(':checked')); //check and uncheck

        var totalPrice = $('.total-price').attr('iprice');
        var currentPrice = cmd.parent().find('.together-prce').attr('iprice');
        var price = 0;
        $('.listTogether li.plcbtnorder').hide();
        if (!chk.is(':checked')) {
            $('.listTogether li[imap$=' + imap + ']').fadeOut();
            $('.listTogether li[imap$=' + imap + ']').next().fadeOut();
            cmd.css({ 'opacity': '.2' });
            price = parseFloat(totalPrice) - parseFloat(currentPrice);
            // khi san pham cuoi cung dc bo chon thi an box co nut order
            if (price > 0) {
                $('.listTogether li.plcbtnorder').fadeIn(1000);
            }
        } else {
            $('.listTogether li[imap$=' + imap + ']').fadeIn();
            $('.listTogether li[imap$=' + imap + ']').next().fadeIn();
            cmd.css({ 'opacity': '1' });
            price = parseFloat(totalPrice) + parseFloat(currentPrice);
            $('.listTogether li.plcbtnorder').fadeIn(1000);
        }
        $('.total-price').text(formatNumber(price) + ' đ');
        $('.total-price').attr('iprice', price);
    });

    //di chuot vao check nao thi anh do border noi bat hon
    $('.together-item-chk input, .together-item-chk span').hover(function () {
        var cmd = $(this);
        var chk = cmd.parent().find('input[name$=together]');
        var imap = chk.attr('imap');
        $('.listTogether li[imap$=' + imap + '] img').toggleClass('hovimg');
    });

    // di chuot vao anh thi danh dau cac check
    $('.listTogether li img').hover(function () {
        var imap = $(this).parent().parent().attr('imap');
        $('.together-check input[imap$=' + imap + ']').parent().find('span').toggleClass('hovimgbg');
    });
    $('.listTogether li:first-child img').hover(function () {
        var imap = $(this).parent().attr('imap');
        $('.together-check input[imap$=' + imap + ']').parent().find('span').toggleClass('hovimgbg');
    });
    //--Add product together seconds
    $('.together-check input[type$=checkbox]').click(function () {
        //alert($(this).attr('checked'));
        var cmd = $(this);
        var imap = cmd.attr('imap');
        var totalPrice = $('.total-price').attr('iprice');
        var currentPrice = cmd.parent().find('.together-prce').attr('iprice');
        var price = 0;
        $('.listTogether li.plcbtnorder').hide();
        if (!cmd.is(':checked')) {
            $('.listTogether li[imap$=' + imap + ']').fadeOut();
            price = parseFloat(totalPrice) - parseFloat(currentPrice);// tinh lai tong gia khi bo chon
            // An box co nut order all khi bo chon toan bo
            if (price > 0) {
                $('.listTogether li.plcbtnorder').fadeIn(1000);
            }
            cmd.parent().find('span').css({ 'opacity': '.2' });// lam mo dong duoc check
            // an dau + khi bo chon
            if (cmd.hasClass('to_x_cs')) {
                $('.listTogether li[imap$=' + imap + ']').next().fadeOut();
            } else if (cmd.hasClass('to_z_cs')) {
                $('.listTogether li[imap$=' + imap + ']').prev().fadeOut();
            } else {
                $('.listTogether li[imap$=' + imap + ']').prev().fadeOut();
            }
        } else {
            $('.listTogether li[imap$=' + imap + ']').fadeIn();
            price = parseFloat(totalPrice) + parseFloat(currentPrice); // tinh lai tong gia khi dc chon
            cmd.parent().find('span').css({ 'opacity': '1' }); // lam mo dong duoc check
            $('.listTogether li.plcbtnorder').fadeIn(1000);//hien box order all
            // an dau + khi dc chon
            if (cmd.hasClass('to_x_cs')) {
                $('.listTogether li[imap$=' + imap + ']').next().fadeIn();
            } else if (cmd.hasClass('to_z_cs')) {
                $('.listTogether li[imap$=' + imap + ']').prev().fadeIn();
            } else {
                $('.listTogether li[imap$=' + imap + ']').prev().fadeIn();
            }
        }

        $('.total-price').text(formatNumber(price) + ' đ');
        $('.total-price').attr('iprice', price);
    });

    // Nut tang giam so luong trong chi tiet san pham
    $('.box-quan a.quan-top').click(function () {
        var _val = $('.box-quan').find('input').val();
        $('.box-quan').find('input').val(parseInt(_val) + 1);
        if (parseInt(_val) > 99) {
            $('.box-quan').find('input').val(99);
        }
    });
    $('.box-quan a.quan-bottom').click(function () {
        var _val = $('.box-quan').find('input').val();
        $('.box-quan').find('input').val(parseInt(_val) - 1);
        if (parseInt(_val) - 1 < 1) {
            $('.box-quan').find('input').val(1);
        }
    });
    $('.box-quan input').change(function () {
        var _val = $(this).val();
        if (parseInt(_val) < 1) {
            $('.box-quan').find('input').val(1);
        }
        if (parseInt(_val) > 99) {
            $('.box-quan').find('input').val(99);
        }
    });
});
//goi phan trang trong muc san pham quan tam

function getInteresPaggin(pIdHis, page, _cmd) {
    var cmd = $(_cmd);
    $.ajax({
        type: 'POST',
        dataType: 'html',
        data: { productIdHis: pIdHis, page: page },
        cache: false,
        url: '/ProductDetail/ProductDetailRight_spquantamPagging',
        success: function (data) {
            //alert(data);
            $('.productCusInteres ul.interesList').html(data);
            $('.interes-pagging a').removeClass('in-ac');
            cmd.addClass('in-ac');
        },
        error: function () {
            Console.log('Khong phan trang duoc product interes');
        }
    });
}


function dinhBoxSpqt() {
    // dinh box san pham duoc quan tan trong product Detail
    if ($('#plcSpqt').hasClass()) {
        var khoangCachTop = $('.productCusInteres').offset().top;
        $('#plcSpqt').css({ 'height': $('.productCusInteres').height() + 'px' });
        $(window).scroll(function () {

            var khoangCachDuoi = $('#footer').offset().top;
            var doCaoBox = $('.productCusInteres').height();
            if ($(window).scrollTop() != 0) {
                //alert(DoCaoBox + '+' + KhoangCachDuoi);
                if ($(window).scrollTop() >= khoangCachTop - 40) {
                    $('.productCusInteres').css({ 'top': '40px', 'position': 'fixed' });
                    $('.productCusInteres').addClass('borderShadow');
                    if ($(window).scrollTop() + doCaoBox >= khoangCachDuoi) {
                        $('.productCusInteres').css({ 'top': (khoangCachDuoi - doCaoBox) + 'px', 'position': 'absolute' });
                        $('.productCusInteres').removeClass('borderShadow');
                    }
                } else {
                    $('.productCusInteres').removeAttr('style');
                    $('.productCusInteres').removeClass('borderShadow');
                }

            } else {
                $('.productCusInteres').removeAttr('style');
                $('.productCusInteres').removeClass('borderShadow');
            }
        });
    }
}

function getPaggingComment(val) {
    var currentPage = parseInt(val);
    var sort = $('.ProductListComment .CommentsortOrder option:selected').val();
    var proId = $('.popup-addrate-login input[name$=pId]').val();
    //alert(proId);
    $.ajax({
        type: 'POST',
        dataType: 'html',
        cache: false,
        url: '/ProductDetail/ProductCommentPagging',
        data: { productId: proId, page: currentPage, sort: sort },
        success: function (data) {
            $('.ProductListComment').html(data);
            //alert(data);
        },
        error: function (e) {
            alert('Đã có lỗi xảy ra');
        }
    });
}
//hien thi hinh anh loading sau khi sumit
//ket thuc an het popup  
function AjaxSubmitReturnData() {
    hideBoxLoginFast();
    setTimeout(function () {
        $('.bgface').click(); //dong tat ca khi xong
    }, 2000);
}

function AjaxSubmitReturnLogin(data) {
    if (data == '0') {
        hideBoxLoginFast();
        setTimeout(function () {
            $('.bgface').click(); //dong tat ca khi xong
            $('.rate-comment-container .rate-comment-none').fadeIn();
            $('.lnkRateLogin').hide();
        }, 2000);
    } else if (data == '1') {
        $('.lnkRateLogin .loginFastEmail').parent().children('.inputError').text('Email này chưa được đăng ký !').show();
    } else if (data == '2') {
        $('.lnkRateLogin .loginFastPass').parent().children('.inputError').text('Mật khẩu chưa chính xác !').show();
    }
}

function hideBoxLoginFast() {
    $('.popup-addrate-login').hide(); //an tam thoi form rate nhanh
    $('body').append('<div class="iconLoading"><img src="/images/icons/gif-load.gif" alt="babo-loading"/></div>');
    var hBody = $('body').height();
    var wBody = $('body').width();
    var top = (hBody - 80) / 2;
    var left = (wBody - 80) / 2;
    $('.iconLoading').css({ 'position': 'fixed', 'top': top + 'px', 'left': left + 'px' });

}

//Add Comment
function AddCommentProductDetail() {
    $('.rate-comment-container .alert-box').fadeIn().delay(5000).fadeOut();
    $('.rate-comment input[name$=txtCommentTitle]').text('');
    $('.rate-comment textarea[name$=txtComment]').text('');
}

// COLOR PRODUCT ---------------------------------------------------------------------------
function LoadEventColor() {
    $('#productColor').val($('.pd-Color a').eq(0).attr('colorname'));
    $('#productColorCode').val($('.pd-Color a').eq(0).attr('colorcode'));
    //show first
    //$('.pd-Color a:eq(0)').addClass('colorSelected');
    $('.pd-Color a:eq(0)').html('<i></i>');
    var proId = $('#productIdRoot').val();
    $('.pd-Color a').click(function () {
        $('.pd-Color a i').remove();
        //$('.pd-Color a').removeClass('colorSelected');
        //$(this).addClass('colorSelected');
        $(this).html('<i></i>');
        $('#productColor').val($(this).attr('colorname'));
        $('#productColorCode').val($(this).attr('colorcode'));
        var co = $(this).attr('idcolor');
        if(co!=undefined && co!=''){
            $('#productId').val(proId + '_' + co);
        }
        var cId = $(this).attr('idcolor');
        //get image by colorid
        $.ajax({
            type: 'POST',
            dataType: 'html',
            cache: false,
            url: '/ProductDetail/ProductImageByColorDetail',
            data: { productId: proId, ColorId: cId },
            success: function (data) {
                $('div.pDetail-img').html(data);
                //alert(data);
                $('.cloud-zoom, .cloud-zoom-gallery').CloudZoom({
                    zoomWidth: '392',
                    zoomHeight: '477'
                });
            },
            error: function (e) {
                alert('Đã có lỗi xảy ra');
            }
        });
    });
}

// SIZE PRODUCT ----------------------------------------------------------------------------
function LoadEventSize() {
    var proId = $('#productId').val();
    //$('.pd-size a:eq(0)').addClass('p-size-selected');

    $('.pd-size a').click(function () {
        //alert('ok')
        $('#productSizeId').val($(this).attr('sizeid'));
        $('#productSizeName').val($(this).text());
        $('#productSizePrice').val($(this).attr('sizeprice'));
        var si = $(this).attr('sizeid');
        if (si != undefined && si != '') {
            $('#productId').val(proId + '_' + si);
        }
        

        if ($('.p-priceOld') != undefined && $('.p-priceOld').length > 0) {
            $('.pd-price').fadeOut(200).text(' ');
            $('.pd-price').text($(this).attr('sizePromotionPriceShow') + ' đ').fadeIn(200);
            $('.p-priceOld').fadeOut(200).text(' ');
            $('.p-priceOld').text($(this).attr('sizePriceShow') + ' đ').fadeIn(200);
        } else {
            $('.pd-price').fadeOut(200).text(' ');
            $('.pd-price').text($(this).attr('sizePriceShow') + ' đ').fadeIn(200);
        }

        $('#rootPriceProduct').val($(this).attr('sizeprice'));
        $('#promotionPrice').val($(this).attr('sizepromotionprice'));

        $('.pd-size a').removeClass('p-size-selected');
        $(this).addClass('p-size-selected');
    });
}





































